import { getValidDate } from '@/dataTransfer/coupon';
import { View } from '@tarojs/components';
import classNames from 'classnames';
import React, { useRef, useState } from 'react';
import ActivityStatus from '../ActivityStatus';
import styles from './index.module.scss';

const OneHeader = ({ activity: { tabName, startTime, endTime } = {}, isShowCountdown }) => {
  if (!isShowCountdown) {
    return null;
  }

  return (
    <View className="one-header">
      <View className="title omit-1">{tabName}</View>

      <ActivityStatus active start={getValidDate(startTime)} end={getValidDate(endTime)} />
    </View>
  );
};

const MultiHeader = ({ activityList, isShowCountdown, value, onChange }) => {
  const scrollDistanceRef = useRef(0);

  const [scrollState, setScrollState] = useState('right');

  return (
    <View
      className={classNames('multi-header', {
        countdown: isShowCountdown,
      })}
      scrollX
      onTouchStart={(e) => {
        const current = e.changedTouches?.[0]?.clientX ?? 0;
        scrollDistanceRef.current = current;
      }}
      onTouchMove={(e) => {
        const distance = scrollDistanceRef.current;
        const current = e.changedTouches?.[0]?.clientX ?? 0;
        scrollDistanceRef.current = current;

        if (current < distance) {
          setScrollState('left');
        } else {
          setScrollState('right');
        }
      }}
    >
      <View className="inner">
        {activityList?.length > 3 && (
          <View className={classNames('scroll', { [scrollState]: true })}></View>
        )}

        {activityList?.map((item) => {
          const { activityId, tabName, startTime, endTime } = item;

          return (
            <View
              className={classNames('wrap', {
                'min-width': activityList.length > 3,
                customePageStyle: value?.activityId === activityId,
              })}
              key={activityId}
              onClick={() => {
                onChange(item);
              }}
            >
              <View className="title">{tabName}</View>

              {isShowCountdown && (
                <ActivityStatus
                  className="status"
                  start={getValidDate(startTime)}
                  end={getValidDate(endTime)}
                  active={value?.activityId === activityId}
                />
              )}
            </View>
          );
        })}
      </View>
    </View>
  );
};

const ActivityHeader = ({ activityList, isShowCountdown, value, onChange }) => {
  return (
    <View className={styles.ActivityHeader}>
      {activityList?.length === 1 && (
        <OneHeader activity={activityList[0]} isShowCountdown={isShowCountdown} />
      )}

      {activityList?.length > 1 && (
        <MultiHeader
          {...{
            activityList,
            value,
            onChange,

            isShowCountdown,
          }}
        />
      )}
    </View>
  );
};

export default ActivityHeader;
